package com.cupk.inspection.controller;


import com.cupk.inspection.model.Task;
import com.cupk.inspection.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/tasks")
@CrossOrigin(origins = "*")
public class TaskController {

    @Autowired
    private TaskService taskService;

    // 创建任务
    @PostMapping
    public ResponseEntity<String> createTask(@RequestBody Task task) {
        if (task.getDevice_id() == null || task.getInspector_id() == null || task.getScheduled_time() == null) {
            return ResponseEntity.badRequest().body("Device_id, inspector_id, and scheduled_time are required");
        }
        taskService.createTask(task);
        return ResponseEntity.ok("Task created successfully");
    }

    // 查询任务
    @GetMapping("/{id}")
    public ResponseEntity<Task> getTask(@PathVariable Long id) {
        Optional<Task> task = taskService.getTaskById(id);
        return task.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // 更新任务状态
    @PutMapping("/{id}")
    public ResponseEntity<String> updateTaskStatus(@PathVariable Long id, @RequestBody Map<String, String> statusUpdate) {
        String status = statusUpdate.get("status");
        if (status == null) {
            return ResponseEntity.badRequest().body("Status is required");
        }
        Task updatedTask = taskService.updateTaskStatus(id, status);
        if (updatedTask != null) {
            return ResponseEntity.ok("Task status updated successfully");
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 获取所有任务
    @GetMapping
    public ResponseEntity<Iterable<Task>> getAllTasks() {
        Iterable<Task> tasks = taskService.getAllTasks();
        if (tasks.iterator().hasNext()) {
            return ResponseEntity.ok(tasks);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}